<template>
  <div>
    <el-dialog
      :title="'编辑开卡奖励'+'：'+name"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      fullscreen
      center
      @close="close"
    >
      <el-form
        ref="form"
        v-loading="loading"
        :model="form"
        :rules="rules"
        class="content"
        label-width="110px"
        size="small"
      >
        <!-- 赠送余额 -->
        <el-form-item label="赠送余额：" prop="giftBalance">
          <el-radio v-model="form.giftBalanceRadio" label="1">不赠送</el-radio>
          <br>
          <el-radio v-model="form.giftBalanceRadio" label="2">赠送余额&nbsp;&nbsp;</el-radio>
          <el-input
            v-model="form.giftBalance"
            :disabled="form.giftBalanceRadio==='1'"
            maxlength="9"
            class="input-append-308"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <!-- 赠送积分 -->
        <el-form-item label="赠送积分：" prop="giftPoints">
          <el-radio v-model="form.giftPointsRadio" label="1">不赠送</el-radio>
          <br>
          <el-radio
            v-model="form.giftPointsRadio"
            :disabled="!enablePoints"
            label="2"
          >赠送积分&nbsp;&nbsp;
          </el-radio>
          <el-input
            v-model="form.giftPoints"
            :disabled="form.giftPointsRadio==='1'||!enablePoints"
            class="input-append-308"
            maxlength="7"
          >
            <template slot="append">个</template>
          </el-input>
          <el-tag v-if="!enablePoints" class="enable-point-tips" type="danger">
            <i class="el-icon-warning" />&nbsp;提示：设置积分相关权益需要开启积分功能，您还未开启&nbsp;&nbsp;
            <span class="link app-text-color-primary" @click="goVipPoints">
              <u>去开启积分功能</u>
            </span>
          </el-tag>
        </el-form-item>

        <!-- 赠送优惠券 -->
        <el-form-item :rules="rules.couponAward" label="赠送卡券：" prop="couponAward">
          <el-radio v-model="form.giftCouponRadio" label="1">不赠送</el-radio>
          <br>
          <el-radio v-model="form.giftCouponRadio" label="3">赠送卡券</el-radio>
          <br>
          <el-radio v-model="form.giftCouponRadio" label="2" disabled="false">赠送券(已弃用)</el-radio>
          <!--          <div v-if="form.giftCouponRadio==='2'" class="nest-card-box">-->
          <!--            <ul>-->
          <!--              <li v-for="(item,index) in form.couponAward" :key="index">-->
          <!--                <el-card :body-style="{ padding: '0 20px' }" shadow="always" class="el-card-coupon">-->
          <!--                  <div class="coupon-list">-->
          <!--                    <el-form-item-->
          <!--                      :prop="'couponAward[' + index + '].couponId'"-->
          <!--                      :rules="rules.couponAwardId"-->
          <!--                      style="display:inline-block"-->
          <!--                    >-->
          <!--                      <div class="coupon-info">-->
          <!--                        <div>-->
          <!--                          券名：{{ item.couponName }}-->
          <!--                          <span-->
          <!--                            class="app-text-color-danger"-->
          <!--                          >{{ invalidCouponIds.includes(item.couponId) ? '(已失效)' : '' }}</span>-->
          <!--                        </div>-->
          <!--                      </div>-->
          <!--                    </el-form-item>-->
          <!--                    <div class="coupon-num">-->
          <!--                      <el-form-item-->
          <!--                        :prop="'couponAward[' + index + '].amount'"-->
          <!--                        :rules="rules.couponAwardAmount"-->
          <!--                        style="display:inline-block"-->
          <!--                      >-->
          <!--                        <el-input-number v-model="item.amount" :min="1" :max="99"/>&nbsp;&nbsp;张&nbsp;&nbsp;-->
          <!--                      </el-form-item>-->
          <!--                      <el-button type="text" style="display:inline" @click="delCardCoupon(index)">删除</el-button>-->
          <!--                    </div>-->
          <!--                  </div>-->
          <!--                </el-card>-->
          <!--              </li>-->
          <!--            </ul>-->
          <!--            <el-button-->
          <!--              :disabled="form.couponAward.length>=10"-->
          <!--              type="text"-->
          <!--              icon="el-icon-plus"-->
          <!--              style="display:block"-->
          <!--              @click="openCouponList"-->
          <!--            >增加券-->
          <!--            </el-button>-->
          <!--          </div>-->
          <div v-if="form.giftCouponRadio==='2'||form.giftCouponRadio==='3'" class="nest-card-box">
            <el-table
              :data="form.couponAward"
              border
              stripe
              size="small"
              empty-text="暂未配置"
              style="width: 100%"
            >
              <el-table-column prop="couponId" label="批次号" />
              <el-table-column prop="couponName" label="卡券名称" />
              <el-table-column prop="couponType" label="卡券类型">
                <template slot-scope="scope">
                  {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] }}
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="数量" width="170px">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'couponAward[' + scope.$index + '].amount'"
                    :rules="rules.couponAwardAmount"
                  >
                    <el-input-number
                      v-model="scope.row.amount"
                      :min="1"
                      :max="99"
                      maxlength="2"
                      label="数量"
                      style="margin-top: 18px"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button type="text" @click="delCardCoupon(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              v-if="form.giftCouponRadio==='3'"
              :disabled="form.couponAward.length>=10"
              type="text"
              icon="el-icon-plus"
              style="display:block"
              @click.native.prevent="openDialogCardCouponTable"
            >增加卡券
            </el-button>
            <!--<el-button-->
            <!--  v-if="form.giftCouponRadio==='2'"-->
            <!--  :disabled="form.couponAward.length>=10"-->
            <!--  type="text"-->
            <!--  icon="el-icon-plus"-->
            <!--  style="display:block"-->
            <!--  @click.native.prevent="openCouponList"-->
            <!--&gt;增加券-->
            <!--</el-button>-->
            <div style="font-size: 12px;color: #606266">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
          </div>
        </el-form-item>
        <!-- 自定义 奖励赠送 -->
        <el-form-item label="自定义奖励：">
          <div v-for="(item, index) in form.customGift" :key="index">
            <el-card class="nest-card-box">
              <div class="flexRBC">
                <div class="app-text-color-primary">奖励 {{ index + 1 }}：</div>
                <el-button type="text" @click.prevent="delCustomAwards(index)">删除</el-button>
              </div>
              <el-form-item
                :prop="'customGift.' + index + '.value'"
                :rules="rules.customGiftValue"
                label="奖励说明："
              >
                <el-input
                  v-model="item.value"
                  :autosize="{ minRows: 2}"
                  type="textarea"
                  placeholder="请输入奖励说明"
                />
              </el-form-item>
              <el-form-item label="奖励说明图：">
                <el-upload
                  :action="actionUrl"
                  :show-file-list="false"
                  :headers="uploadHeaders"
                  :on-success="(res,file)=>{return handleAvatarSuccess(res,file,index)}"
                  :before-upload="beforeAvatarUpload"
                  class="app-uploader-img-plus fl"
                >
                  <img v-if="item.imgUrl" :src="fileBaseUrl+item.imgUrl" class="avatar">
                  <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
                </el-upload>
                <ul class="fl upload_tips">
                  <li>图片要求：</li>
                  <li>1.上传的图片大小不超过500KB，仅支持JPG/PNG格式</li>
                  <li>2.像素大小控制在450像素*200像素以下</li>
                </ul>
              </el-form-item>
            </el-card>
          </div>
          <el-button type="text" icon="el-icon-plus" @click="addCustomAwards">新增自定义奖励</el-button>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button round size="small" @click="hide">取 消</el-button>
        <el-button :disabled="loading" type="primary" round size="small" @click="save">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 券1.0 筛选表格 -->
    <dialog-coupon-list ref="dialogCouponList" />
    <!--券2.0 筛选表格 -->
    <DialogCardCouponTable ref="dialogCardCouponTable" :card-coupon-type="['cash','discount','exchange','cash_wx_pay','times','gift']" :has-checked-ids="hasCheckedCardCouponIds" />
  </div>
</template>

<script>
import DialogCouponList from '@/components/DialogCouponList'
import DialogCardCouponTable from '@/components/DialogCardCouponTable'
import { imgUploadUrl } from '@/api/upload'
import { mapGetters } from 'vuex'
import { getCardReward, editVipCard } from '@/api/vip'
import { getPointsConfig } from '@/api/points'

import {
  validateCustomTwoDecimal,
  validateStrLen,
  validateCustomPositiveInt
} from '@/utils/validate'

export default {
  components: {
    DialogCouponList,
    DialogCardCouponTable
  },
  data() {
    /**
     * 表单校验方法相关
     */
    // 金钱校验
    const validateRmb = (rule, value, callback, text) => {
      if (this.$isNull(value)) {
        callback(new Error(text))
      } else if (!validateCustomTwoDecimal(value, 6)) {
        callback(new Error('请输入0.01~999999.99'))
      } else {
        callback()
      }
    }

    // 开卡赠送余额
    const validateGiftBalance = (rule, value, callback) => {
      if (this.form.giftBalanceRadio === '1') {
        callback()
      } else {
        validateRmb(rule, value, callback, '请输入赠送余额')
      }
    }

    // 开卡赠送积分
    const validateGiftPoints = (rule, value, callback) => {
      if (this.form.giftPointsRadio === '1') {
        callback()
      } else if (value === '') {
        callback(new Error('请输入赠送积分'))
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }

    //  校验优惠券id是否已经过期
    // const validateCouponAwardId = (rule, value, callback) => {
    //   if (value === '') {
    //     callback('请选择优惠券')
    //   } else if (this.invalidCouponIds.includes(value)) {
    //     callback(new Error('该券已过期或已删除，请更换其它券'))
    //   } else {
    //     callback()
    //   }
    // }

    // 优惠券数量
    const validateCouponAwardAmount = (rule, value, callback) => {
      if (value === '') {
        callback('请输入数量')
      } else if (!validateCustomPositiveInt(value, 2)) {
        callback(new Error('请输入正整数'))
      } else {
        this.$refs.form.validateField(['couponAward'])
        callback()
      }
    }

    // 奖励优惠券
    const validateCouponAward = (rule, value, callback) => {
      if (this.form.giftCouponRadio === '1') {
        callback()
        return
      }
      if (!value.length) {
        callback('请至少选择一种')
      } else if (value.length > 10) {
        callback('卡券种类不超过10种')
      } else {
        let maxAmount = 0
        value.forEach(v => {
          if (validateCustomPositiveInt(v.amount, 2)) {
            maxAmount += v.amount
          }
        })
        if (maxAmount > 30) {
          callback('卡券总数量不超过30张')
        } else {
          callback()
        }
      }
    }

    // 自定义奖励说明校验
    const validateCustomGiftValue = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入自定义奖励说明'))
      } else if (!validateStrLen(value, 60)) {
        callback(new Error('长度不超过30个汉字或60个字符'))
      } else {
        callback()
      }
    }
    return {
      /**
       * 表单校验字段相关
       */
      rules: {
        // 赠送余额
        giftBalance: [
          {
            required: true,
            validator: validateGiftBalance,
            trigger: ['blur', 'change']
          }
        ],
        // 赠送积分
        giftPoints: [
          {
            required: true,
            validator: validateGiftPoints,
            trigger: ['blur', 'change']
          }
        ],
        // 优惠券
        // couponAwardId: [
        //   {
        //     required: true,
        //     validator: validateCouponAwardId,
        //     trigger: ['blur', 'change']
        //   }
        // ],
        // 优惠券数量
        couponAwardAmount: [
          {
            required: true,
            validator: validateCouponAwardAmount,
            trigger: ['blur', 'change']
          }
        ],
        couponAward: [
          {
            type: 'array',
            required: true,
            validator: validateCouponAward,
            trigger: ['blur', 'change']
          }
        ],
        // 奖励说明
        customGiftValue: [
          {
            required: true,
            validator: validateCustomGiftValue,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      actionUrl: imgUploadUrl, // 上传地址
      uploadHeaders: {}, // 上传请求头
      // 状态
      dialogVisible: false,
      loading: false,
      enablePoints: true,
      // 数据
      id: '',
      name: '',
      hasCheckedCardCouponIds: [], // 当前已选择的优惠券
      // invalidCouponIds: [], // 失效的优惠券id
      form: {
        giftBalanceRadio: '1', // 赠送余额单选状态
        giftPointsRadio: '1', // 赠送积分单选状态
        giftCouponRadio: '1', // 赠送优惠券单选状态
        giftBalance: 0, // 开卡赠送余额
        giftPoints: 0, // 开卡赠送积分
        couponAward: [], // 开卡赠送优惠券
        customGift: [] // 自定义奖励
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  watch: {
    'form.giftBalanceRadio'(val) {
      if (val === '1') {
        this.$refs.form.clearValidate(['giftBalance'])
      }
    },
    'form.giftPointsRadio'(val) {
      if (val === '1') {
        this.$refs.form.clearValidate(['giftPoints'])
      }
    },
    'form.giftCouponRadio'(newVal, oldVal) {
      if (newVal === '1') {
        this.$refs.form.clearValidate(['couponAward'])
      }
      if (newVal !== '1' && oldVal !== '1') {
        this.form.couponAward = []
      }
    }
  },
  mounted() {
  },
  methods: {
    /**
     * 弹框相关
     */
    open({ id, name }) {
      this.id = id
      this.name = name
      this.initData(id)
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.id = ''
      this.name = ''
      this.hasCheckedCardCouponIds = []
      // this.invalidCouponIds = []
      this.dialogVisible = false
      this.loading = false
      this.enablePoints = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    },

    hide() {
      this.dialogVisible = false
    },

    /**
     * 获取数据
     */
    // 获取表单数据
    initData(id) {
      this.loading = true
      Promise.all([this.getAward(id), this.checkPointConfig()]).finally(() => {
        this.loading = false
      })
    },

    // 获取数据
    getAward(id) {
      return new Promise(resolve => {
        getCardReward(id)
          .then(res => {
            this.resetData(res.data)
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 格式化数据
    resetData(data, resolve) {
      data.giftBalanceRadio = data.giftBalance === 0 ? '1' : '2'
      data.giftPointsRadio = data.giftPoints === 0 ? '1' : '2'
      data.customGift = data.customGift === '' ? [] : JSON.parse(data.customGift)
      data.giftBalance = data.giftBalance / 100 // 换算元
      if (data.couponAward.length) {
        let version = 2 // 判断是v1 还是v2
        // const checkedIds = []
        data.couponAward.some((v, i) => {
          if (i === 0) {
            version = ['CASH', 'DISCOUNT', 'GENERAL'].includes(v.couponType) ? 1 : 2
            return true
          }
          // checkedIds.push(v.couponId)
        })
        // this.hasCheckedCardCouponIds = checkedIds
        data.giftCouponRadio = version === 2 ? '3' : '2'
        // if (version === 1 && this.hasCheckedCardCouponIds.length > 0) this.initCouponList()
      } else {
        data.giftCouponRadio = '1'
        data.couponAward = []
      }
      this.form = data
    },

    // 根据ids获取当前优惠券列表
    // initCouponList() {
    //   const ids = this.hasCheckedCardCouponIds
    //   this.loading = true
    //   getCouponListByIds({ ids })
    //     .then(res => {
    //       if (res.data) {
    //         res.data.forEach(v => {
    //           if (v.status === 3 || v.logicDelete) {
    //             this.invalidCouponIds.push(v.id)
    //           }
    //         })
    //       }
    //     })
    //     .finally(() => {
    //       this.loading = false
    //     })
    // },

    // 积分配置
    checkPointConfig() {
      return new Promise(resolve => {
        getPointsConfig()
          .then(res => {
            this.enablePoints = res.data.enablePoints
          })
          .finally(() => {
            resolve()
          })
      })
    },

    /**
     *  获取数据
     */
    // 保存表单数据
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const data = Object.assign({}, this.form)
          // 赠送金额
          if (data.giftBalanceRadio === '1') {
            data.giftBalance = 0
          } else {
            data.giftBalance = this.$math.mul(data.giftBalance, 100, 0) // 换算分
          }

          // 赠送金额
          if (data.giftPointsRadio === '1') {
            data.giftPoints = 0
          }

          // 优惠券数据处理
          if (data.giftCouponRadio === '1') {
            data.couponAward = []
          }

          // 自定义奖励处理
          data.customGift =
              data.customGift.length >= 1 ? JSON.stringify(data.customGift) : ''
          // 删除多余字段
          delete data.giftBalanceRadio
          delete data.giftPointsRadio
          delete data.giftCouponRadio
          const params = {}
          params.id = this.id
          params.award = data
          this.loading = true
          editVipCard('put', params)
            .then(res => {
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.hide()
              this.resolve && this.resolve()
            })
            .catch(err => {
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    /**
     * 按钮组
     */
    // 跳转积分
    goVipPoints() {
      this.$router.push({
        name: 'VipPoints'
      })
    },

    // 图片上传
    handleAvatarSuccess(res, file, index) {
      if (res.code === 0) {
        this.form.customGift[index].imgUrl = res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },

    // 图片上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 450, 200, 0.5)
    },

    // 新增优惠券
    openCouponList() {
      this.hasCheckedCardCouponIds = []
      this.form.couponAward.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 1).then(res => {
          this.$refs.form.clearValidate(['couponAward'])
          const params = Object.assign({}, res)
          // const params = {
          //   couponId: res.id,
          //   amount: 1,
          //   couponName: res.couponName
          // }
          this.form.couponAward.push(params)
        })
      })
    },

    //  新增优惠券 v2
    openDialogCardCouponTable() {
      this.hasCheckedCardCouponIds = []
      this.form.couponAward.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCardCouponTable.open().then(res => {
          this.$refs.form.clearValidate(['couponAward'])
          this.form.couponAward = this.form.couponAward.concat(res)
        })
      })
    },

    // 删除优惠券
    delCardCoupon(index) {
      this.$refs.form.clearValidate(['couponAward[' + index + '].couponId'])
      this.form.couponAward.splice(index, 1)
      if (this.form.couponAward.length <= 10) {
        this.$refs.form.validateField(['couponAward'])
      }
    },

    // 新增自定义奖励
    addCustomAwards() {
      this.form.customGift.push({
        value: '',
        imgUrl: ''
      })
    },

    // 删除自定义奖励
    delCustomAwards(index) {
      this.form.customGift.splice(index, 1)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.content {
  margin: 0 auto;
  min-width: 900px;
  max-width: 1000px;
}

/* 嵌套卡片 */
.nest-card-box {
  position: relative;
  margin-bottom: 10px;
}

/*  */
.input-append-308 {
  width: 308px;
}

/* 上传 */
.app-uploader-img-plus {
  width: 300px;
  height: 134px;

  .app-uploader-img-plus-icon {
    font-size: 36px;
    color: #8c939d;
    width: 300px;
    height: 134px;
    line-height: 134px;
    text-align: center;
  }

  .avatar {
    width: 300px;
    height: 134px;
    display: block;
  }
}

.upload_tips {
  margin: 20px 0 0 20px;

  li {
    margin-top: 10px;
    font-size: 14px;
    line-height: 16px;
    color: $dark-font-color;
  }
}

/* 券列表 */
//.el-card-coupon {
//  width: 100%;
//  margin-bottom: 10px;
//}
//
//.coupon-list {
//  margin-top: 18px;
//  width: 100%;
//  display: flex;
//  align-items: center;
//  justify-content: space-between;
//
//  .coupon-info {
//    min-width: 250px;
//    color: #606266;
//    margin-right: 20px;
//    line-height: 1.2;
//  }
//}

/* 积分提示 */
.enable-point-tips {
  margin-top: 10px;

  .link {
    cursor: pointer;
  }
}
</style>
